﻿using System;
using System.Collections.Generic;
using System.Linq;
using Bulb.Core.Services.DataStore;
using Cirrious.MvvmCross.Test.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Bulb.Test.RepositoryTests
{
    [TestClass]
    public class RepositoryTests
        : MvxIoCSupportingTest
    {
        public IRepository<BulbItem> MockBulbItemRepository;

        public RepositoryTests()
        {
            IList<BulbItem> bulbs = new List<BulbItem>
            {
                new BulbItem {Id = 0, Name = "Bulb 1", Description = "Description 1", DateTime = new DateTime(2012, 3, 9, 16, 5, 7, 123)},
                new BulbItem {Id = 1, Name = "Bulb 2", Description = "Description 2", DateTime = new DateTime(2013, 3, 9, 16, 5, 7, 123)},
                new BulbItem {Id = 2, Name = "Bulb 2", Description = "Description 3", DateTime = new DateTime(2011, 3, 9, 16, 5, 7, 123)}
            };

            var mockBulbItemRepository = new Mock<IRepository<BulbItem>>();

            mockBulbItemRepository.Setup(mr => mr.All()).Returns(bulbs);

            mockBulbItemRepository.Setup(mr => mr.Latest(It.IsAny<Func<BulbItem, object>>())).Returns((Func<BulbItem, object> func) => bulbs.OrderByDescending(func).FirstOrDefault());

            mockBulbItemRepository.Setup(mr => mr.Get(It.IsAny<int>())).Returns((int id) => bulbs.FirstOrDefault(x => x.Id == id));

            mockBulbItemRepository.Setup(mr => mr.Add(It.IsAny<BulbItem>())).Callback((BulbItem target) =>
                {
                    target.Id = bulbs.Count() + 1;
                    bulbs.Add(target);
                }
            );

            mockBulbItemRepository.Setup(mr => mr.Delete(It.IsAny<BulbItem>())).Callback((BulbItem target) => bulbs.Remove(target));

            mockBulbItemRepository.Setup(mr => mr.Update(It.IsAny<BulbItem>())).Callback((BulbItem target) =>
                {
                    var bulbItem = bulbs.Single(x => x.Id == target.Id);
                    bulbItem = target;
 
                }
            );
            
            mockBulbItemRepository.Setup(mr => mr.Filter(It.IsAny<Func<BulbItem, bool>>())).Returns((Func<BulbItem, bool> func) => bulbs.Where(func).ToList());

            mockBulbItemRepository.Setup(mr => mr.Count()).Returns(bulbs.Count);

            MockBulbItemRepository = mockBulbItemRepository.Object;
        }
    }
}